/*
 * Parse.cpp
 *
 *  Created on: 2017-10-1
 *      Author: hxh
 */

#include "Parse.h"





Parse::Parse() {
	tx_hid = "";
	rx_hid =   "";
	cmd = "";
	index = 520;
	msg = "";
	root=NULL;
}

Parse::~Parse() {

}

string Parse::jsongetstr(string name) {

	cJSON * item = cJSON_GetObjectItem(root,name.c_str());
	if(item)
		return item->valuestring;
	return "";
}

int Parse::jsongetint(string name) {

	cJSON * item = cJSON_GetObjectItem(root,name.c_str());
	if(item)
		return item->valueint;
	return 0;
}

bool Parse::doparse(char* str) {

	root = cJSON_Parse(str);


	tx_hid = jsongetstr("tx_hid");
	rx_hid =   jsongetstr("rx_hid");
	cmd = jsongetstr("cmd");
	index = jsongetint("index");
	//不同的指令不同的处理

	//目前仅仅是发送数据的命令有特殊字段msg，其他都没有
	if(cmd == "tx")
	{
		msg = jsongetstr("msg");
	}
	return true;
}

string Parse::stringify() {

	return "no do";
}

string Parse::map2jsonstr(map<string, Device*> maps) {

	map<string, Device*>::iterator iter;
	cJSON * arr = cJSON_CreateArray();

	for(iter = maps.begin(); iter != maps.end(); iter++)
	{
		cJSON * ob = cJSON_CreateObject();
		cJSON_AddStringToObject(ob,"hid",iter->second->getHid().c_str());
		cJSON_AddStringToObject(ob,"ip",iter->second->getIpaddr().c_str());
		cJSON_AddStringToObject(ob,"lt",iter->second->getLastCommunicationTime().c_str());
		cJSON_AddNumberToObject(ob,"ns",iter->second->getNetStatus());
		cJSON_AddNumberToObject(ob,"ws",iter->second->getWorkStatus());

		cJSON_AddItemToArray(arr,ob);
	}


	char* cstr = cJSON_PrintUnformatted(arr);
	string str(cstr);
	//cout << cstr<<endl;
	cJSON_free(cstr);
	cJSON_Delete(arr);

	return str;

}
